/*
 * Created on 30-ene-2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.juanfrivaldes.cio2005.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.dao.DataAccessException;
import org.springframework.mail.MailException;

import com.juanfrivaldes.cio2005.domain.Usuario;

/**
 * @author root
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class RegistroUsuarioAction extends BaseAction {

	private static Log log = LogFactory.getLog(RegistroUsuarioAction.class);

	protected ActionForward protectedExecute(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (isCancelled(request)) {
			return mapping.findForward("inicio");
		}
		try {
			RegistroUsuarioForm userForm = (RegistroUsuarioForm) form;

			Usuario usuario = new Usuario();
			BeanUtils.copyProperties(usuario, userForm);

			try {
				getCio2005().addUsuario(usuario);
				log.trace("Registro de " + usuario.getEmail() + "--"
						+ usuario.getPassword() + "--" + usuario.getNombre()
						+ "--" + usuario.getApellidos() + "--"
						+ usuario.getNif() + "--" + usuario.getTelefono()
						+ "\n");

				// creamos un usuario nuevo
			} catch (DataAccessException e) {
				log.trace("Registro FALLIDO (DataAccessException) de "
						+ userForm.getEmail() + "--" + userForm.getPassword()
						+ "--" + userForm.getNombre() + "--"
						+ userForm.getApellidos() + "--" + userForm.getNif()
						+ "--" + userForm.getTelefono() + "\n");
				return mapping.findForward("failure");
			}

			try {
				this.getCio2005().sendMailRegistro(usuario);
			} catch (MailException e) {
				log.trace("Envio Fallido de alta a la dirección "
						+ usuario.getEmail() + ":\n" + e.getMessage());
			}

			userForm.setEmail("");
			userForm.setNombre("");
			userForm.setApellidos("");
			userForm.setPassword("");
			userForm.setPasswordCheck("");
			userForm.setNif("");
			userForm.setTelefono("");
			
			request.getSession().setAttribute("currentUser",usuario);
			
		/*	setCurrentUser(usuario);
			addBeanToSession(request, "currentUser", usuario);
*/
		} catch (Exception e) {
			return mapping.findForward("dataFailure");
		}

		return mapping.findForward("success");

	}

}
